package com.yds.socket.client;

import androidx.annotation.NonNull;

import com.yds.socket.CodeType;
import com.yds.socket.bean.OtherMsgBean;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * 作者:     YDS
 * 创建时间: 2023/2/15 13:21
 * 页面描述: 客户端接收信息线程
 */
public class ClientThread extends Thread {

    private final Socket socket;
    private final ClientCallback callback;

    public ClientThread(@NonNull Socket socket, @NonNull ClientCallback callback) {
        this.socket = socket;
        this.callback = callback;
    }

    @Override
    public void run() {
        super.run();
        InputStream inputStream;
        try {
            inputStream = socket.getInputStream();
            if (inputStream.available() == 0) {
                callback.otherMsg(new OtherMsgBean(CodeType.SUCCESS_MSG, "ClientThread inputStream.available() == 0"));
            }
            // 循环获取消息
            while (true) {
                byte[] buffer = new byte[inputStream.available()];
                int size = inputStream.read(buffer);
                if (buffer.length > 0) {
                    byte[] buffers = new byte[size];
                    System.arraycopy(buffer, 0, buffers, 0, size);
                    callback.receiveServerMsg(true, buffers);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            callback.otherMsg(new OtherMsgBean(CodeType.EXCEPTION_MSG, "ClientThread socket IOException " + e.getMessage()));
            byte[] bytes = new byte[0];
            callback.receiveServerMsg(false, bytes);
        }
    }

}
